package com.sikaryofficial.backend.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.excel.EasyExcelFactory;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sikaryofficial.backend.annotation.TenantFilter;
import com.sikaryofficial.backend.domain.dto.req.ProductDeleteReq;
import com.sikaryofficial.backend.domain.dto.req.ProductImageReq;
import com.sikaryofficial.backend.domain.dto.req.ProductListReq;
import com.sikaryofficial.backend.domain.dto.req.QrCodeDownloadListReq;
import com.sikaryofficial.backend.domain.dto.resp.ProductImageVO;
import com.sikaryofficial.backend.domain.dto.resp.QrCodeDownloadDTO;
import com.sikaryofficial.backend.domain.vo.export.ProductExportVO;
import com.sikaryofficial.backend.manager.DataRemoveManager;
import com.sikaryofficial.backend.manager.ProductManager;
import com.sikaryofficial.common.core.domain.R;
import com.sikaryofficial.common.core.exception.ServiceException;
import com.sikaryofficial.common.core.utils.HiResultUtil;
import com.sikaryofficial.common.core.utils.PageUtil;
import com.sikaryofficial.common.core.web.controller.BaseController;
import com.sikaryofficial.common.core.web.domain.HiResult;
import com.sikaryofficial.common.core.web.domain.PageResult;
import com.sikaryofficial.common.log.annotation.Log;
import com.sikaryofficial.common.log.enums.BusinessType;
import com.sikaryofficial.system.api.model.product.BrandTasteDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 品牌口味Controller
 *
 * @author qinjinyuan
 * @date 2023-11-07
 */
@RestController
@RequestMapping("/brandTaste/backend")
@Api(tags = "产品二维码管理")
@Slf4j
@RefreshScope
public class ProductController extends BaseController {
    @Autowired
    private ProductManager productManager;
    @Autowired
    private DataRemoveManager dataRemoveManager;
    @Value("${hismk.product.export.name:ske_product_}")
    private String exportFileName;

    /**
     * 产品二维码生成
     *
     * @return
     */
    @GetMapping("/{brandTasteId}/{visible}")
    @Log(title = "产品可见性设置", businessType = BusinessType.UPDATE)
    @ApiOperation("产品可见性设置")
    @TenantFilter
    public HiResult<Boolean> setVisible(@PathVariable("brandTasteId") Long brandTasteId, @PathVariable("visible") Integer visible) {
        return HiResultUtil.success(productManager.setVisible(brandTasteId, visible));
    }

    /**
     * 1、产品分页列表 ： 产品名称，创建时间搜索【开始和结束时间】
     * 2、产品导入 （产品数据导入）
     * 3、产品导出（产品数据导入）
     * 4、产品删除 （单个 和 批量）
     * 5、产品二维码下载
     */
    @PostMapping("/list")
    @ApiOperation("产品列表")
    @TenantFilter
    public PageResult<BrandTasteDTO> productList(@Validated @RequestBody ProductListReq req) {
        IPage<BrandTasteDTO> page = productManager.productList(req);
        return PageUtil.success(page.getRecords(), page.getTotal());
    }

    @PostMapping("/qrCodeDownloadList")
    @ApiOperation("二维码下载列表")
    @TenantFilter
    public PageResult<QrCodeDownloadDTO> qrCodeDownloadList(@Validated @RequestBody QrCodeDownloadListReq req) {
        IPage<QrCodeDownloadDTO> page = productManager.qrCodeDownloadList(req);
        return PageUtil.success(page.getRecords(), page.getTotal());
    }

    /**
     * 产品删除
     *
     * @param req
     * @return
     */
    @PostMapping("/deleteProduct")
    @Log(title = "产品删除", businessType = BusinessType.DELETE)
    @ApiOperation("产品删除")
    @TenantFilter
    public HiResult<Integer> deleteProduct(@Validated @RequestBody ProductDeleteReq req) {
        return HiResultUtil.success(dataRemoveManager.deleteProduct(req));
    }

    /**
     * 产品导出
     *
     * @param response
     * @param req
     * @throws Exception
     */
    @PostMapping("/export")
    @ApiOperation(value = "产品导出")
    @TenantFilter
    public void productExport(HttpServletResponse response, @RequestBody ProductDeleteReq req) {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");
            String fileName = exportFileName + LocalDateTimeUtil.format(LocalDateTime.now(), DateTimeFormatter.ofPattern(DatePattern.PURE_DATETIME_FORMAT.getPattern()));
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcelFactory.write(response.getOutputStream(), ProductExportVO.class).sheet("ske_product").doWrite(productManager.productExport(req));
        } catch (Exception e) {
            log.error("productExport:{}", e);
            throw new ServiceException("product export error.");
        }
    }

    /**
     * 产品导出模版下载
     *
     * @param response
     * @throws Exception
     */
    @PostMapping("/downloadImportTemplate")
    @ApiOperation(value = "下载产品导入模版")
    @TenantFilter
    public void downloadImportTemplate(HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");
            String fileName = URLEncoder.encode("产品导入模版", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcelFactory.write(response.getOutputStream(), ProductExportVO.class).sheet("ske_product").doWrite(productManager.productExport());
        } catch (Exception e) {
            log.error("productExport:{}", e);
            throw new ServiceException("product export error.");
        }
    }

    /**
     * 产品导入
     *
     * @param excl
     * @return
     */
    @PostMapping("/import")
    @ApiOperation(value = "产品导入")
    @TenantFilter
    public R<String> productImport(@RequestParam("file") MultipartFile excl) {
        beforeCheck(excl);
        productManager.productImport(excl);
        return R.ok("success");
    }

    /**
     * 产品图片保存
     *
     * @param req
     * @return
     */
    @PostMapping("/saveProductImage")
    @Log(title = "保存产品图片", businessType = BusinessType.UPDATE)
    @ApiOperation("保存产品图片")
    @TenantFilter
    public R<String> saveProductImage(@Validated @RequestBody ProductImageReq req) {
        productManager.saveProductImage(req);
        return R.ok("success");
    }

    @GetMapping("/viewProductImage/{brandTasteId}")
    @ApiOperation("查看产品图片")
    @TenantFilter
    public R<ProductImageVO> viewProductImage(@PathVariable("brandTasteId") Long brandTasteId) {
        return R.ok(productManager.viewProductImage(brandTasteId));
    }

    /**
     * 校验文件是否为空
     *
     * @param excl
     */
    private void beforeCheck(MultipartFile excl) {
        if (excl.isEmpty()) {
            throw new ServiceException("文件不能为空");
        }
        String originalFilename = excl.getOriginalFilename();
        if (originalFilename == null || originalFilename.length() == 0) {
            throw new ServiceException("文件名不能为空");
        }
        if (!originalFilename.endsWith(".xlsx")) {
            throw new ServiceException("文件格式不正确,必须是xlsx");
        }
    }
}